package com.mlnx.netty.weice.handler;

import com.mlnx.common.utils.BeanUtils;
import com.mlnx.common.utils.MyLog;
import com.mlnx.netty.base.handler.BaseSimpleChannelInboundHandler;
import com.mlnx.netty.base.message.SugarMessage;
import com.mlnx.weicesugartp.SugarPacket;
import com.mlnx.weicesugartp.SugarResult;
import io.netty.channel.ChannelHandlerContext;

/**
 * Created by amanda.shan on 2019/11/26.
 */
public class WeiceServerHandle extends BaseSimpleChannelInboundHandler<String> {

    private MyLog log = MyLog.getLog(getClass());

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        SugarPacket sugarPacket = new SugarPacket();

        sugarPacket.decode(msg);


        switch (sugarPacket.getCommond()) {
            case SYN_TIME:
                log.info("收到微测血糖时间矫正" + sugarPacket.getCommond());
                ctx.channel().writeAndFlush(sugarPacket.responseSynTime());
                break;
            case MUTIL_UP_SUGAR:
                log.info("收到批量血糖信息" + sugarPacket.getCommond() + sugarPacket.getListSugar().size());
                SugarMessage sugarMessage1 = new SugarMessage();
                sugarMessage1.setImei(sugarPacket.getImei());
                for (SugarResult sugarResult : sugarPacket.getListSugar()
                        ) {
                    BeanUtils.copyProperties(sugarResult, sugarMessage1);
                    sugarMessage1.setTestTime(sugarResult.getTestTime() * 1000);
                    ctx.fireChannelRead(sugarMessage1);
                }
                ctx.channel().writeAndFlush(sugarPacket.responseUpMutilSugar());

                break;
            case UP_DEVICE_INFO:
                ctx.channel().writeAndFlush(sugarPacket.responseUpDevice());
                log.info("收到血糖设备登录消息" + sugarPacket.getCommond() + sugarPacket.getSn());
                break;
            case UP_SUGAR:

                SugarMessage sugarMessage = new SugarMessage();
                sugarMessage.setLabel(sugarPacket.getSugarResult().getLabel());
                sugarMessage.setNormal(sugarPacket.getSugarResult().getNormal());
                sugarMessage.setResult(sugarPacket.getSugarResult().getResult());
                sugarMessage.setSample(sugarPacket.getSugarResult().getSample());
                sugarMessage.setTestTime(sugarPacket.getSugarResult().getTestTime() * 1000);
                sugarMessage.setImei(sugarPacket.getImei());
                ctx.fireChannelRead(sugarMessage);
                ctx.channel().writeAndFlush(sugarPacket.responseUpSugar());
                log.info("收到血糖数据" + sugarPacket.getCommond() + sugarPacket.getSugarResult().getResult());
            default:
                break;
        }
    }

}
